<script setup>


import {defineAsyncComponent, onMounted, reactive, ref, watch} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import axios from "axios";
import {CircleClose, CirclePlus, Download, Open, RefreshRight, Search, Unlock} from "@element-plus/icons-vue";
import UserInfoList from "./UserInfoList.vue";
import UserInfoAdd from "./UserInfoAdd.vue";
import UploadHeaderEdit from "./UploadHeaderEdit.vue";

//========================================编辑======================================================================
const rules = ref({
  account: [
    { required: true, message: '请输入账号', trigger: 'blur' },
  ],
  name: [
    { required: true, message: '请输入用户姓名', trigger: 'blur' },
  ],
  roleId: [
    { required: true, message: '请选择职务', trigger: 'change' },
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1\d{10}$/, message: '请输入正确的11位手机号', trigger: 'blur' }
  ]
});
const form = ref(null);

const avatarUrl = ref('');

const visible4Edit = ref(false);
const user4Edit = ref({
  avatarUrl: ''
})
const editUser = () => {
  // 确保 form.value 是有效的表单实例
  if (form.value) {
    form.value.validate((valid) => {
      if (valid) {
        axios.put('/user/edit', user4Edit.value)
            .then(() => {
              visible4Edit.value = false;
              query();
              ElMessage.success('修改成功');
            })
            .catch(error => {
              // 显示来自后端的错误信息
              const errorMsg = error.response ? error.response.data : '未知错误，请稍后再试';
              ElMessage.error(errorMsg);
            });
      } else {
        console.log('验证失败');
        ElMessage.error('请检查输入的信息');
        return false;
      }
    });
  } else {
    console.error('无法找到表单实例');
  }
};
const show4Edit = type => {
  visible4Edit.value = true;
  let jsonSt = JSON.stringify(type);
  user4Edit.value = JSON.parse(jsonSt);
}

//===================================锁定用户========================================================================

const deleteUser =owner => {
  ElMessageBox.confirm(
      `您确定要锁定账号：${owner.account}吗？`,
      '警告',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        axios.delete(`/user/lock/${owner.id}`)
            .then(() => {
              ElMessage.success('锁定成功!');
              query();
            })
            .catch(error => {
              ElMessage.error(error.response.data);
            })
      })
      .catch(() => {})
}
const lockIds = ref([])
const batchLockIds = lockIdsData =>{
  lockIds.value = lockIdsData;
}

const batchDelete = () => {
  ElMessageBox.confirm(
      `您确定要批量锁定选中的账号吗？`,
      '警告',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        axios.post('/user/batchLock/',lockIds.value)
            .then(() => {
              ElMessage.success('锁定成功!');
              query();
            })
           .catch(error => {
             ElMessage.error(error.response.data);
           })
      })
}

//=============================激活用户======================================================================
const batchActivate = () => {
  ElMessageBox.confirm(
      `您确定要批量激活选中的账号吗？`,
      '警告',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        axios.post('/user/batchActivate/',lockIds.value)
            .then(() => {
              ElMessage.success('激活成功!');
              query();
            })
            .catch(error => {
              ElMessage.error(error.response.data);
            })
      })
}




// ===================================添加=====================================================================
const show4Add = () => {
  visible4Add.value = true;
}

// 添加成功后的回调方法
const handleAddSuccess = () => {
  query();
}

//获取所有职务
const roles = ref([]);

const getRoles = async () => {
  try {
    const resp = await axios.get('/role/getRoles');
    roles.value = resp.data;
  } catch (errorMsg) {
    ElMessage.error(errorMsg);
  }
};



const visible4Add = ref(false);
// ===================================分页显示=========================================================
const reset = () => {
  user4Query.account='';
  user4Query.roleId='';
  user4Query.status=-1
}

const pageNum = ref(1);
const pageSize = ref(10);
const user4Query = reactive({
  account: '',
  roleId: '',
  status: -1,
  pageNum,
  pageSize
})
const userInfos = ref([])
const query = () => {
  axios.post('/user/page', user4Query)
      .then(resp => {
        userInfos.value = resp.data.records;
        total.value = resp.data.total;
        pageNum.value = resp.data.current;
      })
      .catch(errorMsg => {
        ElMessage.error(errorMsg);
      })
}


const total = ref(0)
const handleSizeChange = val => {
  pageSize.value = val;
  query();
}
const handleCurrentChange = val => {
  pageNum.value = val;
  query();

};
// ====================================================================================================================

onMounted(() => {
  query();
  getRoles();
})
</script>


<template>
  <el-row>
    <el-col :span="2">
      <div>
        <hr/>
      </div>
    </el-col>
    <el-col :span="2" style="text-align: center; color: #909399">
      <div>查询条件</div>
    </el-col>
    <el-col :span="20">
      <div>
        <hr/>
      </div>
    </el-col>
  </el-row>


  <el-form :model="user4Query">
    <el-row>
      <el-col :span="6">
        <el-form-item label="账号" label-width="100">
          <el-input v-model="user4Query.account" size="small" autocomplete="off"/>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="职务" label-width="100">
          <el-select v-model="user4Query.roleId" placeholder="请选择职务" clearable>
            <!-- 添加一个默认的 "全部" 选项 -->
            <el-option value="" label="全部"></el-option>
            <el-option v-for="(role,index) in roles" :key="index" :value="role.roleId" :label="role.roleName">
              {{role.roleName}}
            </el-option>
          </el-select>
        </el-form-item>

      </el-col>
      <el-col :span="6" align="middle">
        <el-form-item label="状态" label-width="100">
          <el-radio-group v-model="user4Query.status">
            <el-radio :value=-1>全部</el-radio>
            <el-radio :value="0">未激活</el-radio>
            <el-radio :value="1">激活</el-radio>
            <el-radio :value="2">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
      <el-col :span="2" class="center-content" :offset="1">
        <el-button type="primary" size="small" :icon="Search" round
                   @click="query()">查询
        </el-button>
      </el-col>
      <el-col :span="2" class="center-content">
        <el-button type="warning" size="small" :icon="RefreshRight" round
                   @click="reset()">重置
        </el-button>
      </el-col>


    </el-row>
  </el-form>

  <el-row>
    <el-col :span="24">
      <div>
        <hr style="border-color: #7a73f5;"/>
      </div>
    </el-col>
  </el-row>

  <el-row :gutter="10">
    <el-col :span="3">
      <div style=" display: flex;align-items: center; gap: 8px;">
        <el-icon size="25" color="#7a73f5"><List /></el-icon>  数据管理</div>
    </el-col>
    <el-col :span="2" :offset="14">
      <el-button type="primary" size="small" :icon="CirclePlus" round @click="show4Add">
        添加用户
      </el-button>
    </el-col>
    <el-col :span="2">
    <el-button  type="danger" size="small" round @click="batchDelete()" :icon="CircleClose">批量锁定</el-button>
    </el-col>
    <el-col :span="2">
      <el-button  type="success" size="small" round @click="batchActivate()" :icon="Unlock">批量激活</el-button>
    </el-col>
  </el-row>

  <el-row>
    <el-col :span="24">
      <div>
        <hr style="border-color: #7a73f5;"/>
      </div>
    </el-col>
  </el-row>

  <!-- ========================================分页查询====================================================================== -->
  <el-row>

<UserInfoList :userInfos="userInfos" :pageNum="pageNum" :pageSize="pageSize" :total="total"
              @change-page="handleCurrentChange" @change-page-size="handleSizeChange" @show4EditData="show4Edit"
                @deleteOwner="deleteUser" @batchDelete="batchLockIds">

</UserInfoList>

  </el-row>



  <!-- ========================================编辑弹窗====================================================================== -->

  <el-dialog v-model="visible4Edit"  title="编辑用户信息" width="800px">

    <div class="common-layout">
      <el-container>

        <el-aside width="400px">
          <el-form :model="user4Edit" :rules="rules" ref="form">
            <el-form-item label="账号" label-width="100" prop="account">
              <el-input v-model="user4Edit.account" autocomplete="off"/>
            </el-form-item>
            <el-form-item label="用户姓名" label-width="100" prop="name">
              <el-input v-model="user4Edit.name" autocomplete="off"/>
            </el-form-item>

            <el-form-item label="职务" label-width="100" prop="roleId">
              <el-select v-model="user4Edit.roleId" placeholder="请选择职务">
                <el-option v-for="(role,index) in roles" :key="index" :value="role.roleId" :label="role.roleName">
                  {{role.roleName}}
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="状态" label-width="100">
              <el-radio-group v-model="user4Edit.status">
                <el-radio :value="0">未激活</el-radio>
                <el-radio :value="1">激活</el-radio>
                <el-radio :value="2">锁定</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="联系电话" label-width="100" prop="phone">
              <el-input v-model="user4Edit.phone" autocomplete="off"/>
            </el-form-item>
            <el-form-item label="备注" label-width="100">
              <el-input :rows="3" type="textarea" v-model="user4Edit.remark" autocomplete="off"/>
            </el-form-item>
          </el-form>
        </el-aside>
        <el-container>
          <el-main>

            <UploadHeaderEdit v-model:user4-edit-avatar-url="user4Edit.avatarUrl"  class="move-up" ></UploadHeaderEdit>

          </el-main>
        </el-container>
      </el-container>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible4Edit = false">取消</el-button>
        <el-button type="primary" @click="editUser()">确认</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- ========================================添加弹窗====================================================================== -->

<UserInfoAdd  v-model:visible4-add="visible4Add" @cancel-add="query"  @add-success="handleAddSuccess"
              :roles="roles"></UserInfoAdd>

</template>



<style scoped>


/* 使用 :deep() 穿透样式作用域 */
:deep(.el-table thead th) {
  background-color: #f5f7fa !important;
}


.el-row {
  margin-bottom: 20px;
}

.center-content {
  display: flex;
  justify-content: center; /* 水平居中 */
  margin-top: 3px;
}

.move-up {
  margin-top: -60px; /* 向上移动20像素 */
}

</style>